#  This file is part of FlickFleck.
#  Copyright (C) 2008 Jyke Tapani Jokinen
#
#    FlickFleck is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    FlickFleck is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with FlickFleck.  If not, see <http://www.gnu.org/licenses/>.
#

import os, os.path
import sys
import shutil
import ui

# ------------------------------------------------------------------------
# in win32 add quotes around path (there can be spaces in names)
# XXX: spaces in filepaths should be worked out int UNIX too
def quotepath( path ):
    if sys.platform == 'win32':
        return '"' + path + '"'
    else:
        return path

# ------------------------------------------------------------------------
# stops if we cannot access the named file
def verify_access( file ):
    if not os.access( file, os.F_OK ):
        ui.ERR( "fileops.access: %s: access denied" % file )

# ------------------------------------------------------------------------
# tries to do a safe copy from 'orig_file' to 'new_file'
#
def copy( orig_file, new_file ):
    f_from = os.path.normpath( orig_file )
    f_to   = os.path.normpath( new_file )

    # if copying to itself
    if f_from == f_to:
        ui.ERR( "fileops.copy: copying a file to itself? (%s)" % f_from )

    # we should be able to access fromfile
    verify_access( f_from )

    # target should not exists (caller should make sure of this)
    if os.path.exists( f_to ):
        ui.ERR( "fileops.copy: target file exists (%s)" % f_to )

    try:
        shutil.copy2( f_from, f_to )  # preserves attributes
    except:
        ui.ERR("fileops.copy: copy2 operation failed (%s)" % f_from)

    # do some sanity checks to the file we just created
    verify_access( f_to )
    if os.path.getsize( f_to ) < 1:
        ui.ERR("fileops.copy: target filesize zero (%s)" % f_to )
    

#
# debug/testing
#
if __name__ == '__main__':
    import sys
    import tempfile
    sys.path.insert("..")
    filename1 = tempfile.mktemp (".txt")
    open (filename1, "w").close ()
    filename2 = filename1 + ".copy"
    print filename1, "=>", filename2
    copy( filename1, filename2 )
